const Base = require('../../base.js');

module.exports = class extends Base {
  async indexAction() {
    let id = this.get('id')
    let userInfo = await this.session('user_info')
    /// 判断用户是否已登录
    if (!userInfo) return this.fail(-1, '未授权操作')
    /// 判断是否传入ID
    if (!id) return this.fail(-1, '参数错误')
    // 把id转成objID
    let _id
    try { _id = think.objId(id) } catch (e) {}
    if (!_id) return this.fail(-1, '参数错误')
    // 查看任务是存在
    let task = await this.model('task/index').info(id)
    if (!task) return this.fail(-1, '任务不存在')
    // 查看任务是否还有数量
    if (task.get_num >= task.num) return this.fail(-1, '任务已被领取完了，试试别的任务吧')
    // 查看用户是否领取过这个任务
    let task_result = await this.model('task_result/index').getUserResult(userInfo._id, task._id)
    if (task_result) return this.fail(-1, '您已经领取过这个任务了')
    // 查看用户是否达到领取限制
    let user = await this.model('user/index').info(userInfo._id)
    let vipNum = think.vipNum(user.vip || 0)
    let dayTime = think.dayTime()
    let task_result_num = await this.model('task_result/index').count({
      uid: userInfo._id,
      create_at: {
        $gte: dayTime.start,
        $lte: dayTime.end, 
      }
    })
    if (task_result_num >= vipNum.num) return this.fail(-1, '可领取任务上线，请明天在来吧')
    // 查看用户是否符合任务等级
    if (task.reward >= vipNum.money) return this.fail(-1, '当前任务需要升级VIP才可以领取')
    // 可以领取 创建任务回复
    task_result = await this.model('task_result/index').create(userInfo._id, task._id)
    this.json({
      status: 200,
      message: 'success'
    })
  }
};
